package com.dingup.provider.service.classInfo.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingup.api.Util.ClassRoomUtil;
import com.dingup.api.Util.DateUtil;
import com.dingup.api.adapter.classInfo.ClassInfoAdapter;
import com.dingup.api.adapter.student.StudentCourseInformationAdapter;
import com.dingup.api.bean.response.SelectBean;
import com.dingup.api.bean.response.classInfo.ClassInfoResponseSelectBean;
import com.dingup.api.enums.ClassUserTypeEnum;
import com.dingup.api.enums.ExamTypeEnum;
import com.dingup.api.enums.StudentCampusEnum;
import com.dingup.api.model.classInfo.ClassInfo;
import com.dingup.api.model.classInfo.ClassUserInfo;
import com.dingup.api.model.student.StudentCourseInformation;
import com.dingup.api.model.sys.SysUser;
import com.dingup.provider.feign.client.paike.user.PaikeUserFeignClient;
import com.dingup.provider.mapper.ClassInfoMapper;
import com.dingup.provider.mapper.ClassUserInfoMapper;
import com.dingup.provider.mapper.StudentCourseInformationMapper;
import com.dingup.provider.mapper.SysUserMapper;
import com.dingup.provider.service.classInfo.ClassUserInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by wancheng on 2018/8/30.
 */
@Service
public class ClassUserInfoServiceImpl implements ClassUserInfoService {

    private static Logger logger = LoggerFactory.getLogger(ClassUserInfoServiceImpl.class);

    @Autowired
    ClassUserInfoMapper classUserInfoMapper;
    @Autowired
    ClassInfoMapper classInfoMapper;
    @Autowired
    StudentCourseInformationMapper studentCourseInformationMapper;
    @Autowired
    PaikeUserFeignClient paikeUserFeignClient;
    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public void needInsert(List<ClassUserInfo> needInsert, String operaUserId, Integer classId) {
        ClassInfo classInfo = classInfoMapper.selectByPrimaryKey(classId);
        Integer lessonId = classInfo.getLessonId();
        //operaUserId classId用来记录日志
        needInsert.stream().forEach(
                classUserInfo -> {
                    insert(classUserInfo, classId, lessonId);
                }
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void needDelete(List<ClassUserInfo> needDelete, String operaUserId, Integer classId) {
        ClassInfo classInfo = classInfoMapper.selectByPrimaryKey(classId);
        Integer lessonId = classInfo.getLessonId();
        //operaUserId classId用来记录日志
        needDelete.stream().forEach(
                classUserInfo -> {
                    delete(classUserInfo, operaUserId, classId, lessonId);
                }
        );
    }

    @Override
    public void insert(ClassUserInfo classUserInfo, Integer classId, Integer lessonId) {
        if (classUserInfo.getType().equals(ClassUserTypeEnum.STUDENT)) {
            StudentCourseInformation param = new StudentCourseInformation();
            param.setLessonId(lessonId);
            param.setUserId(classUserInfo.getUserId());
            param.setClassId(classId);
            List<StudentCourseInformation> courses = studentCourseInformationMapper.getByUserIdAndLessonIdAndClassId(param);
            if (courses != null && courses.size() > 0) {
                StudentCourseInformation studentCourseInformation = courses.get(0);
                StudentCourseInformation update = new StudentCourseInformation();
                update.setId(studentCourseInformation.getId());
                update.setClassId(classId);
                studentCourseInformationMapper.updateByPrimaryKeySelective(update);
                logger.info("添加学生,修改学生课程信息 param={}", JSONObject.toJSONString(update));
            } else {
                StudentCourseInformation studentCourseInformation = new StudentCourseInformation();
                studentCourseInformation.setLessonId(lessonId);
                studentCourseInformation.setUserId(classUserInfo.getUserId());
                studentCourseInformation.setClassId(classId);
                studentCourseInformation.setCreateTime(new Date());
                List<StudentCourseInformationAdapter> self = studentCourseInformationMapper.getByUserId(classUserInfo.getUserId());
                if (self != null && self.size() > 0) {
                    studentCourseInformation.setIfRenewStudent(true);
                }
                studentCourseInformationMapper.insertSelective(studentCourseInformation);
                logger.info("添加学生,新增学生课程信息 param={}", JSONObject.toJSONString(studentCourseInformation));
            }
        }
        paikeUserFeignClient.addStudent(classUserInfo);
        classUserInfoMapper.insertSelective(classUserInfo);
        logger.info("添加学生 classUserInfo={}", JSONObject.toJSONString(classUserInfo));

    }


    @Override
    public void delete(ClassUserInfo classUserInfo, String operaUserId, Integer classId, Integer lessonId) {
        StudentCourseInformation param = new StudentCourseInformation();
        param.setLessonId(lessonId);
        param.setClassId(classId);
        param.setUserId(classUserInfo.getUserId());
        List<StudentCourseInformation> courses = studentCourseInformationMapper.getByUserIdAndLessonIdAndClassId(param);
        if (courses != null && courses.size() > 0) {
            StudentCourseInformation studentCourseInformation = courses.get(0);
            if (studentCourseInformation.getContributionAmount() == null || studentCourseInformation.getSalerId() == null) {
                //删除学生未完成的成单信息
                studentCourseInformationMapper.deleteByPrimaryKey(studentCourseInformation.getId());
            } else {

            }
        }
        //删除学生未完成的课节信息
        paikeUserFeignClient.deleteStudent(classUserInfo);
        classUserInfoMapper.deleteByPrimaryKey(classUserInfo.getId());
    }

    @Override
    public List<String> getStudentIdsByTeacherId(String teacherId, ClassUserTypeEnum teacherType) {
        return classUserInfoMapper.getStudentIdsByTeacherId(teacherId, teacherType);
    }

    @Override
    public List<ClassInfoResponseSelectBean> getClassInfo(Integer classId) {
        List<ClassInfoAdapter> classInfoAdapters = classInfoMapper.getClassInfoAdapter(classId, false);
        List<ClassInfoResponseSelectBean> response = new ArrayList<>();
        classInfoAdapters.stream().forEach(
                a -> {
                    ClassInfoResponseSelectBean bean = new ClassInfoResponseSelectBean();
                    bean.setValue(String.valueOf(a.getId()));
                    bean.setLabel(a.getClassName());
                    bean.setCampus(StudentCampusEnum.getEnum(a.getLessonInfo().getLessonCampus()));
                    Map<ClassUserTypeEnum, List<ClassUserInfo>> memberMap = a.getMembers().stream().collect(Collectors.groupingBy(ClassUserInfo::getType));
                    List<SelectBean> subjectInfos = a.getSubjectInfos().stream().map(e -> {
                        return new SelectBean(e.getNameCh(), e.getNameCh());
                    }).collect(Collectors.toList());
                    bean.setSubjects(subjectInfos);
                    if (!CollectionUtils.isEmpty(memberMap.get(ClassUserTypeEnum.STUDENT))) {
                        List<SelectBean> students = memberMap.get(ClassUserTypeEnum.STUDENT).stream().map(e -> {
                            return new SelectBean(e.getUserName(), e.getUserId());
                        }).collect(Collectors.toList());
                        bean.setStudents(students);
                    }
                    if (!CollectionUtils.isEmpty(memberMap.get(ClassUserTypeEnum.TEACHER))) {
                        List<SelectBean> teachers = memberMap.get(ClassUserTypeEnum.TEACHER).stream().map(e -> {
                            return new SelectBean(e.getUserName(), e.getUserId());
                        }).collect(Collectors.toList());
                        bean.setTeacher(teachers);
                    }
                    response.add(bean);
                }
        );
        return response;
    }

    @Override
    public ClassInfoAdapter getClassInfoById(Integer classId) throws Exception {
        List<ClassInfoAdapter> classInfoAdapters = classInfoMapper.getClassInfoAdapter(classId, null);
        ClassInfoAdapter adapter = null;
        if (!CollectionUtils.isEmpty(classInfoAdapters) && classInfoAdapters.size() == 1) {
            adapter = classInfoAdapters.get(0);
        } else {
            throw new Exception("不存在或有多条记录");
        }
        Map<ClassUserTypeEnum, List<ClassUserInfo>> memberMap = adapter.getMembers().stream().collect(Collectors.groupingBy(ClassUserInfo::getType));
        if (!CollectionUtils.isEmpty(memberMap.get(ClassUserTypeEnum.STUDENT))) {
            adapter.setStudents(memberMap.get(ClassUserTypeEnum.STUDENT));
        }
        if (!CollectionUtils.isEmpty(memberMap.get(ClassUserTypeEnum.TEACHER))) {
            adapter.setTeachers(memberMap.get(ClassUserTypeEnum.TEACHER));
        }
        if (!CollectionUtils.isEmpty(memberMap.get(ClassUserTypeEnum.CLASSTEACHER))) {
            adapter.setClassTeacher(memberMap.get(ClassUserTypeEnum.CLASSTEACHER).get(0));
        }
        if (StringUtils.isNotEmpty(adapter.getLessonInfo().getLessonCampus())) {
            adapter.setSchoolCampusMap(StudentCampusEnum.getMap(adapter.getLessonInfo().getLessonCampus()));
            adapter.setCampusRooms(ClassRoomUtil.getCampusRooms(StudentCampusEnum.getEnum(adapter.getLessonInfo().getLessonCampus())));
        }
        if (StringUtils.isNotEmpty(adapter.getLessonInfo().getExam())) {
            adapter.setExam(ExamTypeEnum.getMap(adapter.getLessonInfo().getExam()));
        }
        if (adapter.getBeginTime() != null) {
            adapter.setBeginTimeString(DateUtil.dateToStringForPk(adapter.getBeginTime()));
        }
        if (adapter.getEndTime() != null) {
            adapter.setEndTimeString(DateUtil.dateToStringForPk(adapter.getEndTime()));
        }
        if (!CollectionUtils.isEmpty(adapter.getSubjectInfos())) {
            List<SelectBean> selectBeen = adapter.getSubjectInfos().stream().map(s -> new SelectBean(s.getNameCh(), s.getNameCh())).collect(Collectors.toList());
            adapter.setLessonSubjectInfos(selectBeen);
        }
        adapter.setLessonName(adapter.getLessonInfo().getLessonName());
        adapter.clean();
        return adapter;
    }

    @Override
    public Map<String, Object> getUserGroupByClassSelf(Integer classId) {
        List<ClassUserInfo> student = classUserInfoMapper.getUserByClassId(classId, ClassUserTypeEnum.STUDENT);
        List<SelectBean> studentSelectBean = student.stream().map(s -> new SelectBean(s.getUserName(), s.getUserId())).collect(Collectors.toList());
        List<ClassUserInfo> teacher = classUserInfoMapper.getUserByClassId(classId, ClassUserTypeEnum.TEACHER);
        List<SelectBean> teacherSelectBean = teacher.stream()
                .map(t -> new SelectBean(t.getUserName(), t.getUserId()))
                .collect(Collectors.toList());
        List<String> teacherIds = teacher.stream().map(ClassUserInfo::getUserId).collect(Collectors.toList());
        List<SysUser> allTeachers = sysUserMapper.getAllUserNameAndUserIds(true);
        List<SelectBean> otherTeachers = allTeachers.stream()
                .filter(t -> !teacherIds.contains(t.getUserId()))
                .map(t -> new SelectBean(t.getUserName(), t.getUserId()))
                .collect(Collectors.toList());
        List<Map<String, Object>> teacherMap = new ArrayList<>();
        Map<String, Object> selfMap = new HashMap<>();
        selfMap.put("label", "该班级的老师");
        selfMap.put("options", teacherSelectBean);
        teacherMap.add(selfMap);
        Map<String, Object> otherMap = new HashMap<>();
        otherMap.put("label", "其他老师");
        otherMap.put("options", otherTeachers);
        teacherMap.add(otherMap);
        Map<String, Object> res = new HashMap<>();
        res.put("student", studentSelectBean);
        res.put("teacher", teacherMap);
        return res;
    }

    @Override
    public void deleteUser(String userId) {
        classUserInfoMapper.deleteUser(userId);
    }

}
